package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类，定时处理订单状态
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理支付超时订单
     */
    @Scheduled(cron = "0 * * * * ?") //每分钟触发一次
    public void processTimeoutOrder() {
        log.info("定时处理支付超时订单，当前时间：{}", LocalDateTime.now());
        //将超时的最迟下单时间
        LocalDateTime latestOrderTime = LocalDateTime.now().plusMinutes(-15);
        //查询是否存在支付超时订单
        List<Orders> orders = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, latestOrderTime);
        log.info("超时订单数：{}",orders.size());
        //如果存在则将订单改为取消状态，并说明取消原因
        if (orders != null && orders.size() > 0) {
            for (Orders order : orders) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("超时未支付，自动取消");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }
    }

    /**
     * 处理一直处于派送中状态的订单
     */
    @Scheduled(cron = "0 0 1 * * ?") //每天1点触发一次
    public void processDeliveryOrder() {
        log.info("定时处理上一日派送中状态订单，当前时间：{}", LocalDateTime.now());
        //下单时间节点为凌晨12点
        LocalDateTime time = LocalDateTime.now().plusHours(-1);
        //查询上一日订单中是否仍有处于派送中状态的
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        log.info("仍处于派送中状态订单数：{}",ordersList.size());
        //如果有则将订单状态改为已完成
        if (ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }

}
